import { WebView } from '@hips/taro-ui'
import { navigateTo, redirectTo } from '@tarojs/taro'
import { setToken, setStorage, getToken, queryToMap, removeToken } from 'tools'
import { getUserInfo } from 'request/api'
import {
  BASE_URL,
  CLIENT_ID,
  DEFAULT_TOKEN,
  DEFAULT_PAGE
} from 'tools/constant'
export default {
  name: 'AppLogin',
  onLoad() {
    this.init()
  },
  computed: {
    token() {
      return getToken()
    }
  },
  methods: {
    /**
     * 页面初始化
     * @returns
     */
    async init() {
      if (!this.token && !DEFAULT_TOKEN) return
      let url = `/pages/application/index`
      DEFAULT_TOKEN && setToken(DEFAULT_TOKEN)
      try {
        const userInfo = await getUserInfo()
        const { tenantId } = userInfo
        setStorage('user-info', { tenantId })
        DEFAULT_PAGE && (url = DEFAULT_PAGE)
        redirectTo({
          url
        })
      } catch (e) {
        removeToken()
        console.error('发生异常:' + e)
      }
    },

    /**
     * webView 加载成功
     * @param {*} data
     * @returns
     */
    loadSuccess(data) {
      if (DEFAULT_PAGE && DEFAULT_TOKEN && DEFAULT_TOKEN === this.token) return
      const {
        detail: { src }
      } = data
      let url = `/pages/application/index`
      const haveParams = src.split('#')[1]
      const queryMap = queryToMap(haveParams)
      DEFAULT_PAGE && (url = DEFAULT_PAGE)
      //URL含参数的话直接带参跳转
      if (queryMap.has('access_token')) {
        queryMap.has('tenantId') && setStorage('user-info', { tenantId })
        setToken(queryMap.get('access_token'))
        navigateTo({
          url
        })
      }
    }
  },
  render() {
    const href = `${BASE_URL}/oauth/oauth/authorize?response_type=token&client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent(
      `${BASE_URL}/oauth/login?`
    )}`
    return <WebView src={href} onLoad={this.loadSuccess} />
  }
}
